<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="8" :hidden="true">
            <a-form-model-item label="流程名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle" >
              <a-input :max-length="255" :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入流程名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="htbh">
              <a-input :disabled="true" v-model="model.htbh" placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <j-date :disabled="true" placeholder="请选择申请时间" v-model="model.createTime" style="width: 100%"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
              <select-user-by-dep disabled :multi="false" v-model="model.proposer"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
              <j-select-depart :disabled="true" v-model="model.proposerDeptId"/>
            </a-form-model-item>
          </a-col>

          <a-divider>基本信息</a-divider>
          <template v-if="sfbg">
            <a-col :span="8">
              <a-form-model-item label="合同编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="caId">
                <select-contract-manager-input
                  :disabled="formDisabled"
                  v-model="model.caId"
                  :allList="true"
                  :status = "'2'"
                  :muitFlag = "true"
                  :changeStatus = "'unchanged'"
                  @change="htbhChange"
                  :triggerChange="true"/>
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :span="8">
            <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="htmc">
              <a-input :disabled="formDisabled" v-model="model.htmc" placeholder="请输入合同名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="合同类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="htlx">
              <j-dict-select-tag
                :disabled="formDisabled ? true : sfbg"
                type="list"
                v-model="model.htlx"
                dictCode="htlx_type"
                placeholder="请选择合同类型"
                @change="htlxChange"
                :triggerChange="true"/>
            </a-form-model-item>
          </a-col>

          <template v-if="sfbg">
            <a-col :span="8">
              <a-form-model-item label="变更类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bglx">
                <j-dict-select-tag
                  :disabled="formDisabled"
                  type="list"
                  v-model="model.bglx"
                  dictCode="bglx_type"
                  placeholder="请选择变更类型"/>
              </a-form-model-item>
            </a-col>
          </template>

          <a-col :span="8">
            <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xmmc">
              <select-project-input
                ref="projectModel"
                :disabled="formDisabled"
                v-model="model.xmmc"
                :proDisabled="true"
                :isContractManager="true"
                :projectStatus="'2'"
                @change="xmmcChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" style="display:none">
            <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xmbh">
              <a-input :disabled="true" v-model="model.xmbh" placeholder="请输入项目编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="jytd">
              <select-team-input
                :disabled="formDisabled"
                v-model="model.jytd"
                :tdlx="1"/>

            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yjgsnd">
              <j-dict-select-tag
                :disabled="formDisabled"
                type="list"
                v-model="model.yjgsnd"
                dictCode="yjgsnd"
                placeholder="请选择业绩归属年度"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qddw">
              <select-Company-input :disabled="formDisabled" v-model="model.qddw" placeholder="请选择签订单位"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xmcjr">
              <select-user-by-dep :disabled="formDisabled" :multi="false" v-model="model.xmcjr"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yzdw">
              <select-customer-input
                :disabled="formDisabled"
                v-model="model.yzdw"
                commercialType="1"
                @change="yzdwChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lxr">
              <j-dict-select-tag
                :disabled="formDisabled"
                type="list"
                v-model="model.lxr"
                :dictCode="cust_lxr"
                placeholder="请选择联系人"
                @change="lxrChange"
                :triggerChange="true"/>

            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lxfs">
              <a-input :disabled="formDisabled" v-model="model.lxfs" placeholder="请输入联系方式"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="签订日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qdrq">
              <j-date disabled placeholder="请选择签订日期" v-model="model.qdrq" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="是否用印" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sfyz">
              <j-dict-select-tag
                :disabled="formDisabled"
                type="radio"
                v-model="model.sfyz"
                dictCode="yn"
                @input="handleChangeSeal"
                placeholder="请选择是否用印"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="isShowSeal">
            <a-form-model-item label="印章类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yzlx">
              <j-multi-select-tag
                :disabled="formDisabled"
                type="select"
                v-model="model.yzlx"
                dictCode="yzlx_type"
                placeholder="请选择印章类型"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="isShowSeal">
            <a-form-model-item label="用印份数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yyfs">
              <a-input-number
                :disabled="formDisabled"
                :max="99999999"
                :min="0"
                v-model="model.yyfs"
                placeholder="请输入用印份数"
                style="width: 100%"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="48" v-if="!isShowSeal">
          <a-col :span="12">
            <a-form-model-item label="合同原件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="masterCopy">
              <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.masterCopy"></j-upload>
              <a-button v-else icon="download" @click="viewFile(model.masterCopy)">文件列表</a-button>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="关联收款合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="glskht">
              <j-dict-select-tag
                :disabled="formDisabled ? true : isFkht ? false : true"
                type="radio"
                v-model="model.glskht"
                dictCode="yn"
                placeholder="请选择关联收款合同"
                @change="glskhtChange"
                :triggerChange="true"/>
            </a-form-model-item>
          </a-col>
          <template v-if="glhtFlag">
            <a-col :span="8">
              <a-form-model-item label="收款合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skhtmc">
                <select-contract-manager-input
                  :muitFlag = "true"
                  :disabled="formDisabled"
                  v-model="model.skhtmc"
                  htlx="1"
                  @back="skhtBack"
                  :allList="true"
                  :triggerChange="true"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="收款合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skhte">
                <a-input-number
                  disabled
                  :max="99999999"
                  :min="0"
                  v-model="model.skhte"
                  placeholder="请输入收款合同额"
                  style="width: 100%"
                  @blur="convertMoney1"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="收款合同额大写" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="skhtedx">
                <a-input disabled v-model="model.skhtedx" placeholder="请输入收款合同额大写"></a-input>
              </a-form-model-item>
            </a-col>
          </template>
        </a-row>
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="本次合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bchte">
              <a-input-number
                :precision="2"
                :disabled="formDisabled"
                :max="99999999"
                :min="0"
                v-model="model.bchte"
                placeholder="请输入本次合同额"
                style="width: 100%"
                @change="convertMoney2"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="本次合同额大写" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bchtedx">
              <a-input :disabled="true" v-model="model.bchtedx" placeholder="请输入本次合同额大写"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="服务期限" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fwqx">
              <j-date :disabled="formDisabled" placeholder="请选择服务期限" v-model="model.fwqx" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="是否涉及多方信息" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="involveMultiple">
              <j-dict-select-tag
                :disabled="formDisabled"
                type="radio"
                v-model="model.involveMultiple"
                @input="(val) => this.involveMultipleFlag = val == 1"
                dictCode="yes_no"
                placeholder="请选择是否涉及多方信息"/>
            </a-form-model-item>
          </a-col>

          <!-- 是否涉及多方信息为是时展示 -->
          <template v-if="involveMultipleFlag">
            <a-divider style="top:20px;">{{ this.firstTitle }}</a-divider>
            <a-col :span="24">
              <div style="margin-bottom: 6px;margin-top: 6px">
                <a-button @click="handleAdd4" v-if="!formDisabled" type="primary">新增</a-button>
              </div>
              <a-table
                ref="table"
                size="middle"
                rowKey="id"
                :loading="loading"
                :columns="columns4"
                :pagination="false"
                :data-source="dataSource4">
                <span slot="action" slot-scope="text, record">
                  <template v-if="!formDisabled">
                    <a @click="handleEdit4(record)">编辑</a>
                    <a-divider type="vertical"/>
                    <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete4(record.id)">
                      <a>删除</a>
                    </a-popconfirm>
                  </template>
                </span>
              </a-table>
            </a-col>

            <a-divider style="top:20px;">{{ this.secondTitle }}</a-divider>
            <a-col :span="24">
              <div style="margin-bottom: 6px;margin-top: 6px">
                <a-button @click="handleAdd3" v-if="!formDisabled" type="primary">新增</a-button>
              </div>
              <a-table
                ref="table"
                size="middle"
                rowKey="id"
                :loading="loading"
                :columns="columns3"
                :pagination="false"
                :data-source="dataSource3">
                <span slot="action" slot-scope="text, record">
                  <template v-if="!formDisabled">
                    <a @click="handleEdit3(record)">编辑</a>
                    <a-divider type="vertical"/>
                    <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete3(record.id)">
                      <a>删除</a>
                    </a-popconfirm>
                  </template>
                </span>
              </a-table>
            </a-col>
          </template>
          <a-divider style="top:20px;">任务信息</a-divider>
            <a-col :span="24">
              <j-vxe-table
                ref="vTable"
                row-number
                keep-source
                height="auto"
                :loading="loading"
                :dataSource="dataSource2"
                :columns="columns2"
                style="margin-top: 8px;"
                @valueChange="handleValueChange"
              >
              </j-vxe-table>
            </a-col>
          <a-divider style="top:20px;">收付款计划</a-divider>
          <template v-if="sfbg">
            <a-col :span="8">
              <a-form-model-item label="是否变更款项信息" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sfbgkxxx">
                <j-dict-select-tag
                  :disabled="formDisabled"
                  type="radio"
                  v-model="model.sfbgkxxx"
                  dictCode="yn"
                  :triggerChange="true"
                  @change="handleChangeSfbgkxxx"
                  placeholder="请选择是否变更款项信息"/>
              </a-form-model-item>
            </a-col>
          </template>

            <a-col :span="24">
              <div style="margin-bottom: 6px;margin-top: 6px" v-if="showKxxx">
                <a-button @click="handleAdd" v-if="!formDisabled" type="primary">新增</a-button>
              </div>
              <a-table
                ref="table"
                size="middle"
                rowKey="id"
                :scroll="{x:'100%'}"
                :loading="loading"
                :columns="columns"
                :pagination="false"
                :data-source="dataSource">
                <span slot="action" slot-scope="text, record">
                  <template v-if="!formDisabled && showKxxx">
                    <a @click="handleEdit(record)">编辑</a>
                     <span v-if="sfbg && !record.finalId ">
                        <a-divider type="vertical"/>
                        <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                          <a >删除</a>
                        </a-popconfirm>
                     </span>
                  </template>
                </span>
              </a-table>
            </a-col>


          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bz">
              <a-textarea :maxLength="500" :disabled="formDisabled" v-model="model.bz" rows="4" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="邮寄信息" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="yjxx">
              <a-textarea :maxLength="500" :disabled="formDisabled" v-model="model.yjxx" rows="4" placeholder="请输入邮寄信息"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="12">
            <a-form-model-item label="相关附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="xgfj">
              <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.xgfj"></j-upload>
              <a-button v-else icon="download" @click="viewFile(model.xgfj)">文件列表</a-button>
            </a-form-model-item>
          </a-col>

          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form-model>
      <view-file-modal ref="viewFileModal"></view-file-modal>
      <!--收付款计划-->
      <erp-omc-contract-manager-plan-modal :bchte="remainBchte" ref="itemList" @ok="modalFormOk"></erp-omc-contract-manager-plan-modal>
      <erp-omc-contract-manager-class-modal ref="itemList2" @ok="modalFormOk2"></erp-omc-contract-manager-class-modal>
      <erp-omc-contract-manager-trustee-modal
        ref="itemList3"
        @ok="modalFormOk3"></erp-omc-contract-manager-trustee-modal>
      <erp-omc-contract-manager-entrust-modal
        ref="itemList4"
        @ok="modalFormOk4"></erp-omc-contract-manager-entrust-modal>
    </j-form-container>
  </a-spin>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'
import { viewFile } from '@/utils/util'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
import SelectContractInput from '@/views/scy/components/SelectContractInput'
import { convertCurrency } from '@/utils/MoneyConvert'
import ViewFileModal from '@/views/scy/components/ViewFileModal'
import ErpOmcContractManagerPlanModal from '../modules/ErpOmcContractManagerPlanModal'
import ErpOmcContractManagerClassModal from '../modules/ErpOmcContractManagerClassModal'
import ErpOmcContractManagerTrusteeModal from '../modules/ErpOmcContractManagerTrusteeModal'
import ErpOmcContractManagerEntrustModal from '../modules/ErpOmcContractManagerEntrustModal'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import SelectContractManagerInput from '@/views/scy/components/SelectContractManagerInput'
import moment from 'moment';
import { mapGetters } from 'vuex';
import { message } from 'ant-design-vue'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'

export default {
  name: 'ErpOmcContractManagerForm',
  mixins: [viewFile],
  components: { // select-customer-input
    SelectProjectInput,
    SelectTeamInput,
    SelectUserByDep,
    SelectCustomerInput,
    SelectContractInput,
    ViewFileModal,
    ErpOmcContractManagerPlanModal,
    ErpOmcContractManagerClassModal,
    ErpOmcContractManagerTrusteeModal,
    ErpOmcContractManagerEntrustModal,
    SelectContractManagerInput,
    SelectCompanyInput
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {
        sfyz: 0,
        glskht: 0,
        sfbgkxxx: 0,
        jf: undefined,
        yf: undefined,
        involveMultiple: 0
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        bpmBizTitle: [
          { required: true, message: '请输入流程名称!' },
        ],
        htlx: [
          { required: true, message: '请输入合同类型!' }
        ],
        htmc: [
          { required: true, message: '请输入合同名称!' }
        ],
        xmmc: [
          { required: true, message: '请输入项目名称!' }
        ],
        jytd: [
          { required: true, message: '请输入经营团队!' }
        ],
        yjgsnd: [
          { required: true, message: '请输入业绩归属年度!' }
        ],
        qddw: [
          { required: true, message: '请输入签订单位!' }
        ],
        xmcjr: [
          { required: true, message: '请输入项目承接人!' }
        ],
        yzdw: [
          { required: true, message: '请输入业主单位!' }
        ],
        // qdrq: [
        //   { required: true, message: '请输入签订日期!' }
        // ],
        yzlx: [
          { required: true, message: '请选择印章类型!' }
        ],
        yyfs: [
          { required: true, message: '请填写用印份数!', trigger: 'blur' },
          { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
        ],
        lxfs: [
          { required: false },
          { pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!' }
        ],
        masterCopy: [
          { required: true, message: '请上传合同原件!'  }
        ]
      },
      url: {
        add: '/api/erp/omc/contractmanager/erpOmcContractManager/add',
        edit: '/api/erp/omc/contractmanager/erpOmcContractManager/edit',
        queryById: '/api/erp/omc/contractmanager/erpOmcContractManager/queryById',
        queryPlanList: '/api/erp/omc/contractmanager/erpOmcContractManagerPlan/listAll',
        queryClassList: '/api/erp/omc/contractmanager/erpOmcContractManagerClass/listAll',
        queryClassList2: '/api/erp/omc/project/erpOmcProjectTask/list',
        queryEntrustList: '/api/erp/omc/contractmanager/erpOmcContractManagerEntrust/listAll',
        queryTrusteeList: '/api/erp/omc/contractmanager/erpOmcContractManagerTrustee/listAll',
        generatedFormNumber: '/api/erp/base/generatedFormNumber'
      },
      loading: false,
      columns: [
        {
          title: '款项名称',
          align: 'center',
          dataIndex: 'kxmc',
           ellipsis: true,
        },
        {
          title: '金额(元)',
          align: 'center',
          dataIndex: 'je',
           ellipsis: true,
        },
        {
          title: '款项日期',
          align: 'center',
          dataIndex: 'kxrq',
           ellipsis: true,
        },
        {
          title: '款项节点说明',
          align: 'center',
          dataIndex: 'kxjdsm',
           ellipsis: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      columns2: [
        {
          title: '业务编码',
          align: 'center',
          key: 'ywfl',
          formatter: ({ cellValue}) => {
            return cellValue ? filterMultiDictText(this.dictOptions['ywfl'], cellValue + '') : ''
          }
        },
        {
          title: '业务名称',
          align: 'center',
          key: 'ywmc'
        },
        {
          title: '合同占比(%)',
          align: 'center',
          key: 'htzb',
          type: JVXETypes.inputNumber,
        },
        {
          title: '分配合同额（元）',
          align: 'center',
          key: 'fphte',
          type: JVXETypes.inputNumber,
        },
        {
          title: '生产团队',
          align: 'center',
          key: 'sctd_dictText',
          // formatter: ({ cellValue }) => {
          //   return cellValue ? filterMultiDictText(this.dictOptions['sctd'], cellValue + '') : ''
          // }
        },
        {
          title: '团队负责人',
          align: 'center',
          key: 'tdfzr_dictText',
          // formatter: ({ cellValue }) => {
          //   return cellValue ? filterMultiDictText(this.dictOptions['tdfzr'], cellValue + '') : ''
          // }
        }
      ],
      columns3: [
        {
          title: '名称',
          align: 'center',
          dataIndex: 'gsdaId',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['gsda'], text + '')
            }
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      detailColumns: [
        {
          title: '名称',
          align: 'center',
          dataIndex: 'gsdaId',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['gsda'], text + '')
            }
          }
        },
        {
          title: '业务编码',
          align: 'center',
          dataIndex: 'ywfl',
        },
        {
          title: '业务名称',
          align: 'center',
          dataIndex: 'ywmc'
        },
        {
          title: '合同占比(%)',
          align: 'center',
          dataIndex: 'htzb',
        },
        {
          title: '分配合同额（元）',
          align: 'center',
          dataIndex: 'fphte',
        },
        {
          title: '生产团队',
          align: 'center',
          dataIndex: 'sctd_dictText',
        },
        {
          title: '团队负责人',
          align: 'center',
          dataIndex: 'tdfzr_dictText',
        }
      ],
      columns4: [
        {
          title: '名称',
          align: 'center',
          dataIndex: 'khdaId',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['khda'], text + '')
            }
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      dataSource: [], // 收付款计划数据源
      dataSource2: [], // 任务信息
      dataSource3: [], // 受托方信息
      dataSource4: [], // 委托方信息
      dictOptions: {},
      firstTitle: '委托方信息',
      secondTitle: '受托方信息',
      cust_lxr: 'erp_omc_customer_manager_contact,lxr,id',
      glhtFlag: false,
      sfbg: false,
      detailFlag: false,  //查看详情状态
      isFkht: false,
      showKxxx: false,
      // 修改时加上当前行的值
      editRemain: 0,
      involveMultipleFlag: false
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
    isShowSeal () {
      if (this.model.sfyz && this.model.sfyz == 1) {
        return true
      } else {
        return false
      }
    },
    // 合同额剩余可分配值
    remainBchte(){
      if(this.model.bchte){
        let remain = this.model.bchte + this.editRemain;
        this.dataSource.forEach(data=>{
          remain -= data.je;
        })
        return remain;
      }else{
        return 0;
      }
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    // 如果是流程中表单，则需要加载流程表单data
    this.showFlowData();
    this.initDictConfig();
  },
  methods: {
    initDictConfig() {
      initDictOptions('ywfx_type').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'ywfl', res.result)
        }
      })
      //
      // initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'sctd', res.result)
      //   }
      // })
      //
      // initDictOptions('erp_employee_file,name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'tdfzr', res.result)
      //   }
      // })

      initDictOptions('erp_purchase_supplier,enterprise_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'khda', res.result)
        }
      })

      initDictOptions('erp_company_files,file_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'gsda', res.result)
        }
      })
    },
    handleAdd() {
      this.$refs.itemList.add();
      this.$refs.itemList.title = '新增';
      this.$refs.itemList.disableSubmit = false;
      this.isFkht = false;
    },
    handleEdit(record) {
      // 修改时将当前的值从remain中减去
      this.editRemain = record.je;
      this.$refs.itemList.edit(record);
      this.$refs.itemList.title = '修改';
      this.$refs.itemList.disableSubmit = false;
    },
    handleDelete(id) {
      for (let i = 0; i < this.dataSource.length; i++) {
        if (this.dataSource[i].id == id) {
          this.dataSource.splice(i, 1);
        }
      }
    },
    handleAdd2() {
      this.$refs.itemList2.add();
      this.$refs.itemList2.title = '新增';
      this.$refs.itemList2.disableSubmit = false;
    },
    handleEdit2(record) {
      this.$refs.itemList2.edit(record);
      this.$refs.itemList2.title = '修改';
      this.$refs.itemList2.disableSubmit = false;
    },
    handleDelete2(id) {
      for (let i = 0; i < this.dataSource2.length; i++) {
        if (this.dataSource2[i].id == id) {
          this.dataSource2.splice(i, 1);
        }
      }
    },
    handleAdd3() {
      this.$refs.itemList3.add();
      this.$refs.itemList3.title = '新增';
      this.$refs.itemList3.disableSubmit = false;
    },
    handleEdit3(record) {
      this.$refs.itemList3.edit(record);
      this.$refs.itemList3.title = '修改';
      this.$refs.itemList3.disableSubmit = false;
    },
    handleDelete3(id) {
      for (let i = 0; i < this.dataSource3.length; i++) {
        if (this.dataSource3[i].id == id) {
          this.dataSource3.splice(i, 1);
        }
      }
    },
    handleAdd4() {
      this.$refs.itemList4.add();
      this.$refs.itemList4.title = '新增';
      this.$refs.itemList4.disableSubmit = false;
    },
    handleEdit4(record) {
      this.$refs.itemList4.edit(record);
      this.$refs.itemList4.title = '修改';
      this.$refs.itemList4.disableSubmit = false;
    },
    handleDelete4(id) {
      for (let i = 0; i < this.dataSource4.length; i++) {
        if (this.dataSource4[i].id == id) {
          this.dataSource4.splice(i, 1);
        }
      }
    },
    modalFormOk(data) {
      this.loading = true;
      let flag = true;
      // debugger;
      for (let i = 0; i < this.dataSource.length; i++) {
        if (this.dataSource[i].id == data.id) {
          this.dataSource.splice(i, 1, data);
          flag = false;
        }
      }
      if (flag) {
        this.dataSource.push(data);
      }
      this.loading = false;
    },
    modalFormOk2(data) {
      if(!data.ywmc) return false // 如果没有填写数据
      this.loading = true;
      let flag = true;
      // debugger;
      for (let i = 0; i < this.dataSource2.length; i++) {
        if (this.dataSource2[i].ywfl == data.ywfl) {
          this.dataSource2.splice(i, 1, data);
          flag = false;
        }
      }
      if (flag) {
        this.dataSource2.push(data);
      }
      this.loading = false;
    },
    modalFormOk3(data) {
      this.loading = true;
      let flag = true;
      // debugger;
      for (let i = 0; i < this.dataSource3.length; i++) {
        if (this.dataSource3[i].id == data.id) {
          this.dataSource3.splice(i, 1, data);
          flag = false;
        }
      }
      if (flag) {
        this.dataSource3.push(data);
      }
      this.loading = false;
    },
    modalFormOk4(data) {
      this.loading = true;
      let flag = true;
      // debugger;
      for (let i = 0; i < this.dataSource4.length; i++) {
        if (this.dataSource4[i].id == data.id) {
          this.dataSource4.splice(i, 1, data);
          flag = false;
        }
      }
      if (flag) {
        this.dataSource4.push(data);
      }
      this.loading = false;
    },
    yzdwChange() {
      this.$set(this.model, 'lxr', undefined);
      // this.cust_lxr = erp_omc_customer_manager_contact,lxr,id;
      this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
      // this.$set(this.model, 'lxr', undefined);
      // this.$set(this.model, 'lxfs', undefined);
    },
    lxrChange(val) {
      //debugger
      getAction('/api/erp/omc/customermanager/erpOmcCustomerManagerContact/queryById', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          // debugger;
          // this.model.lxdh = data.lxfs;
          this.$set(this.model, 'lxr', val)
          this.$set(this.model, 'lxfs', data.lxfs)
        }
      })
    },
    ...mapGetters(['userInfo']),
    add() {
      this.dataSource = []
      this.dataSource2 = []
      this.dataSource3 = []
      this.dataSource4 = []
      this.modelDefault.lx = 1
      this.sfbg = false;
      this.edit(this.modelDefault);
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      this.model.proposer = this.userInfo().empId;
      this.model.proposerDeptId = this.userInfo().deptId;
      this.showKxxx = true;
      this.involveMultipleFlag = false;
      this.generatedFormNumber();
    },
    generatedFormNumber() {
      getAction(this.url.generatedFormNumber, { prefix: 'HT', subSystemCode: '05' }).then(res => {
        if (res.success) {
          this.$set(this.model, 'htbh', res.result)
        }
      })
    },
    add2() {
      this.dataSource = []
      this.dataSource2 = []
      this.dataSource3 = []
      this.dataSource4 = []
      this.modelDefault.lx = 2
      this.sfbg = true
      this.edit(this.modelDefault);
      this.model.proposer = this.userInfo().empId;
      this.model.proposerDeptId = this.userInfo().deptId;
      this.showKxxx = false;
      this.involveMultipleFlag = false;
      this.generatedFormNumber();
    },
    edit(record) {
      this.$refs.form.resetFields();
      this.model = Object.assign({}, record);
      if (record.lx == 2) {
        this.sfbg = true
        this.$set(this.validatorRules,'caId',[{ required: true, message: '请选择合同编号!' }])
        this.$set(this.validatorRules,'bglx',[{ required: true, message: '请选择变更类型!' }])
      } else {
        this.sfbg = false;
        this.$delete(this.validatorRules,'caId')
        this.$delete(this.validatorRules,'bglx')
      }
      if (this.model && this.model.htlx) {
        if (this.model.htlx === '1' || this.model.htlx === 1) {
          this.changeTitle()
        } else {
          this.changeTitle(1)
        }
      } else {
        this.changeTitle()
      }
      this.$set(this, 'isFkht', this.model.htlx != '1')
      this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
      if (this.model.id) {
        // 收款计划
        getAction(this.url.queryPlanList, { mainId: this.model.id }).then((res) => {
          if (res.success) {
            this.dataSource = res.result || res.result.records
          }
        })

        getAction(this.url.queryClassList, { mainId: this.model.id }).then((res) => {
          if (res.success) {
            this.dataSource2 = res.result.records || res.result

          }
        })
        // 任务信息

        // 受托方信息
        getAction(this.url.queryTrusteeList, { mainId: this.model.id }).then((res) => {
          if (res.success) {
            this.dataSource3 = res.result.records || res.result
          }
        })

        // 委托方信息
        getAction(this.url.queryEntrustList, { mainId: this.model.id }).then((res) => {
          if (res.success) {
            this.dataSource4 = res.result.records || res.result
          }
        })
        this.showKxxx = this.model.lx == 2 ? this.model.sfbgkxxx == '1' : true
        this.glhtFlag = this.model.glskht == '1' ? true : false
      }
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      // this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id';
      // this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
      this.involveMultipleFlag = record.involveMultiple == 1
      this.visible = true;
    },
    // 渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId };
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.detailFlag = true;
            this.edit(res.result);
          }
        });
      }
    },
    submitForm() {
      const that = this;
      // 判断收款计划金额是否大于合同金额
      let planSum = 0;
      this.dataSource.forEach(data=>{
        planSum += data.je;
      });
      if(this.model.bchte<planSum){
        message.warning("计划总金额超出合同金额!")
        this.$emit('unButtonDisable');
        return;
      }
      let total = 0
      this.dataSource2.forEach(val => {
        total += val.fphte
      })
      if(total !== this.model.bchte){
        message.warning('分配项金额和本次合同额不相等，请重新填写')
        this.$emit('unButtonDisable');
        return;
      }
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          if (that.model.htlx === 1 || that.model.htlx === '1') {
            if (that.dataSource.length === 0) {
              that.$message.warn('请填写收付款计划');
              that.confirmLoading = false
              that.$emit('unButtonDisable');
              return;
            }
          }
          let model = {};
          Object.assign(model, this.model)
          // if (model.bchte) {
            // this.$set(this.model,"yjhte",yjhte * 100)
          //   model.bchte = model.bchte * 100;
          // }

          // 收付款计划
          model.planList = this.dataSource;

          // for (let i = 0; i < model.planList.length; i++) {
          //   // debugger;
          //   model.planList[i].je = model.planList[i].je * 100
          // }

          model.classList = this.dataSource2;
          model.trusteeList = this.dataSource3;
          model.entrustList = this.dataSource4;

          // debugger;

          httpAction(httpurl, model, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
              that.$emit('unButtonDisable');
            }
          }).catch((error) => {
            that.$emit('unButtonDisable');
          }).finally(() => {
            that.confirmLoading = false;
          })
        } else {
          that.$emit('unButtonDisable');
        }
      })
    },
    convertMoney1() {
      let money = this.model.skhte
      this.$set(this.model, 'skhtedx', convertCurrency(money))
    },
    convertMoney2() {
      let money = this.model.bchte
      this.$set(this.model, 'bchtedx', convertCurrency(money))
      this.dataSource2.forEach((item, index) => {
        item.finalId = item.id
        if (this.model.bchte && item.htzb) {
          // item.fphte = this.model.bchte * item.htzb / 100
          let amount = item.fphte / this.model.bchte * 100
          item.htzb = Math.round((amount + Number.EPSILON) * 100) / 100;
        }
      })
    },
    handleValueChange(event){
      const { rowIndex, columnIndex,value } = event
      if(this.model.bchte){
        if(columnIndex == 3){
          let amount = this.model.bchte * value / 100
          this.dataSource2[rowIndex].fphte = Math.round((amount + Number.EPSILON) * 100) / 100;
        } else if (columnIndex == 4){
          let rate = value / this.model.bchte * 100
          this.dataSource2[rowIndex].htzb = Math.round((rate + Number.EPSILON) * 100) / 100;
        }
      }
    },
    xmmcChange(val) {
      getAction('/api/erp/omc/project/erpOmcProject/queryById', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$set(this.model, 'yzdw', data.ownerUnit) // 业主单位
          // debugger;
          // this.model.lxdh = data.lxfs;
          this.$set(this.model, 'xmbh', data.finalNo) // 项目编号
          this.$set(this.model, 'jytd', data.teamName) // 经营团队
          this.$set(this.model, 'yjgsnd', data.year) // 业绩归属年度
          this.$set(this.model, 'qddw', data.signUnit) // 签定单位
          this.$set(this.model, 'xmcjr', data.undertaker) // 项目承接人
          this.$set(this.model, 'lxfs', data.contactTel) // 联系方式
          this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
          this.$set(this.model, 'lxr', data.contacts) // 联系人
          // 任务信息
          getAction(this.url.queryClassList2, { pageNo:1,pageSize: 999,projectId: data.id }).then((res) => {
            this.dataSource2 = []
            if (res.success) {
              let data = res.result.records || res.result
              // debugger;
              for (let i = 0; i < data.length; i++) {
                let d = {
                  'ywfl': data[i].categoryCode,
                  'ywmc': data[i].categoryName,
                  'htzb': data[i].contractRate,
                  'fphte': data[i].contractAmount,
                  'sctd': data[i].productTeam,
                  'sctd_dictText': data[i].productTeam_dictText,
                  'tdfzr': data[i].teamLeader,
                  'tdfzr_dictText': data[i].teamLeader_dictText,
                  'projectTaskId': data[i].id
                };
                let index = this.dataSource2.findIndex(item => item.ywfl == d.ywfl)
                if(index > -1){
                  this.dataSource2.splice(index, 1, d)
                }else{
                  this.dataSource2.push(d);
                }
              }
            }
          })
        }
      })
    },
    htlxChange(val) {
      this.$set(this.model, 'htlx', val)
      if (val) {
        let url;
        if (val === '1') {
          // 合同类型为收款合同，需要做特殊处理
          // updated  by wuzx at 2021/12/28 调整为立项底表查询,不带bpmStatus
          // 修改前:  url = '/api/erp/omc/project/erpOmcProjectApply/list2?bpmStatus=3&isSkht=true";
          // 修改后:
          url = '/api/erp/omc/project/erpOmcProject/list2?isSkht=true';
          this.$set(this.model, 'glskht', '0')
          this.glhtFlag = false;
          this.changeTitle()
        } else {
          // 合同类型为收款合同，需要做特殊处理
          // updated by wuzx at 2021/12/28 调整为立项底表查询,不带bpmStatus
          // 修改前: url = '/api/erp/omc/project/erpOmcProjectApply/list2?bpmStatus=3&isSkht=false";
          // 修改后:
          url = '/api/erp/omc/project/erpOmcProject/list2?isSkht=false';
          this.changeTitle(1)
        }
        this.$set(this, 'isFkht', val !== '1');
        this.$refs.projectModel.loadData(url);
      }
    },
    glskhtChange(val) {
      this.$set(this.model, 'glskht', val)
      if (val) {
        if (val === '1') {
          this.glhtFlag = true;
        } else {
          this.glhtFlag = false;
        }
      }
    },
    changeTitle(args) {
       if (args === 1) {
         this.firstTitle = '受托方信息'
         this.secondTitle = '委托方信息'
       } else {
         this.firstTitle = '委托方信息'
         this.secondTitle = '受托方信息'
       }
    },
    htbhChange(val) {
      getAction('/api/erp/omc/contractmanager/erpOmcContractManagerFinal/queryById', { id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
          // debugger;
          this.$set(this.model, 'caId', val)
          this.$set(this.model, 'htmc', data.htmc) // 合同名称
          this.$set(this.model, 'htlx', data.htlx) // 合同类型
          this.$set(this.model, 'xmmc', data.xmmc) // 项目名称
          this.$set(this.model, 'jytd', data.jytd) // 经营团队
          this.$set(this.model, 'yjgsnd', data.yjgsnd)// 业绩归属年度
          this.$set(this.model, 'qddw', data.qddw) // 签订单位
          this.$set(this.model, 'xmcjr', data.xmcjr) // 项目承认人
          this.$set(this.model, 'yzdw', data.yzdw)// 业主单位
          this.$set(this.model, 'lxr', data.lxr)// 联系人
          this.$set(this.model, 'lxfs', data.lxfs) // 联系方式
          this.$set(this.model, 'qdrq', data.qdrq)// 签订日期
          this.$set(this.model, 'sfyz', data.sfyz)// 是否用章
          this.$set(this.model, 'yzlx', data.yzlx) // 印章类型
          this.$set(this.model, 'yyfs', data.yyfs)// 用印份数
          this.$set(this.model, 'glskht', data.glskht) // 关联收款合同
          this.glhtFlag = data.glskht == '1'
          this.$set(this.model, 'skhtmc', data.skhtmc) // 收款合同名称
          // this.$set(this.model, 'jf', data.yzdw) // 甲方
          this.$set(this.model, 'jf', data.jf)// 甲方
          this.$set(this.model, 'yf', data.yf)// 甲方
          // this.$set(this.model, 'yf', data.qddw) // 已方
          this.$set(this.model, 'skhte', data.skhte)// 收款合同额
          this.$set(this.model, 'skhtedx', data.bchtedx)// 收款合同额大写

          let bchte = data.bchte;
          // if (data.bchte) {
          //   bchte = data.bchte / 100
          // }

          this.$set(this.model, 'bchte', bchte)
          this.$set(this.model, 'bchtedx', data.bchtedx)
          this.$set(this.model, 'fwqx', data.fwqx)
          this.$set(this.model, 'bz', data.bz) // 备注
          this.$set(this.model, 'yjxx', data.yjxx) // 邮寄信息
          this.$set(this.model, 'xgfj', data.xgfj) // 相关附件
          this.$set(this.model, 'htbh', data.htbh) // 合同编号
          this.$set(this.model, 'xmbh', data.xmbh) // 合同编号

          this.$set(this.model, 'bglx', data.bglx)
          this.$set(this.model, 'sfbgkxx', data.sfbgkxx)
          //this.$set(this.model, 'proposer', data.proposer)
          //this.$set(this.model, 'proposerDeptId', data.proposerDeptId)
          this.$set(this, 'isFkht', data.htlx != '1')
          this.$set(this.model, 'involveMultiple', data.involveMultiple)
          this.$set(this, 'involveMultipleFlag', data.involveMultiple == 1)
          this.$set(this.model, 'masterCopy', data.masterCopy) // 合同原件
          //this.yzdwChange();

          // 收款计划
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerPlanFinal/listAll', { mainId: val }).then((res) => {
            if (res.success) {
              this.dataSource = res.result.records || res.result
              if (this.dataSource.length > 0) {
                this.dataSource.forEach((item, index) => {
                  item.finalId = item.id
                })
              }
            }
          })

          // 任务信息
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerClassFinal/listAll', { mainId: val }).then((res) => {
            if (res.success) {
              this.dataSource2 = res.result.records || res.result
              this.dataSource2.forEach((item, index) => {
                item.finalId = item.id
                if (this.model.bchte && item.htzb) {
                  item.fphte = this.model.bchte * item.htzb / 100
                }
              })
            }
          })

          // 受托方信息
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerTrusteeFinal/listAll', { mainId: val }).then((res) => {
            if (res.success) {
              this.dataSource3 = res.result.records || res.result
              this.dataSource3.forEach((item, index) => {
                item.finalId = item.id
              })
            }
          })

          // 委托方信息
          getAction('/api/erp/omc/contractmanager/erpOmcContractManagerEntrustFinal/listAll', { mainId: val }).then((res) => {
            if (res.success) {
              this.dataSource4 = res.result.records || res.result
              this.dataSource4.forEach((item, index) => {
                item.finalId = item.id
              })
            }
          })
        }
      })
    },
    skhtBack (item) {
      //this.$set(this.model, 'skhtmc', item[0].htmc)
      this.$set(this.model, 'jf', item[0].qddw)
      this.$set(this.model, 'skhte', item[0].bchte)
      this.$set(this.model, 'skhtedx', item[0].bchtedx)
    },
    handleChangeSfbgkxxx(val) {
      this.$set(this.model, 'sfbgkxxx', val);
      this.$set(this, 'showKxxx', val == '1');
    },
    handleChangeSeal(val) {
      if (val == 0) {
        this.$set(this.validatorRules, 'masterCopy', [{ required: true, message: '请上传合同原件!'  }]);
      } else {
        this.$delete(this.validatorRules, 'masterCopy');
      }
    }
  }
}
</script>
